/*
 * @Author: liaoxin
 * @Date: 2022-03-08 17:34:36
 * @LastEditors: Setsuna
 * @LastEditTime: 2023-07-20 18:24:50
 * @FilePath: \src\pages\CustomerManage\Customer\List\DealerDataTable\DealerDataTable.tsx
 */
import React from 'react'
import {
  http,
  columnRenders,
  UdModal,
  UdModalForm,
  uaaApp,
  UdDrawer,
  UdFilter,
  UdToolbar,
  UdTable,
  IUdColumn,
} from '@/lib'
import _ from 'lodash'
import { Select, Button, Input, message, Spin, TreeSelect } from 'antd'
import { WrappedFormUtils } from 'antd/lib/form/Form'
import customerApis from '@/apis/CustomerManage'
import anounApis from '@/apis/AnnouncementManage'
import udMainStore from '@/store/UdMain'
import { validators } from '@/lib/utils/validators'
import { downBlobFile } from '@/utils/methods'
import UdSelect from '@/components/UdFormControls/UdSelect'
import apis from '@/apis'
import SelectLowerTable from './SelectLowerTable'
import { withRouter } from 'react-router-dom'
import CustomerDetailsTable from '../TerminalDataTable/CustomerDetailsTable'

const Option = Select.Option
const { TreeNode } = TreeSelect
const AddBtnAuth = 'user_customers_agent_add'
const exportCustomersTable = 'user_customers_agent_export'
const DetailBtnAuth = 'user_customer_manager_find_kids'
const EditBtnAuth = 'user_customers_agent_put'
const BrandBtnAuth = 'user_customers_agent_brand'

class DealerDataTable extends React.PureComponent<any, any> {
  private filterForm: WrappedFormUtils = {} as WrappedFormUtils
  private brandList = udMainStore.brandList
  private columns: IUdColumn<any>[] = [
    { title: '序号', dataIndex: 'id', key: 'id', width: 50, render: (text, reoled, index) => index + 1 },
    { title: '客户编码', dataIndex: 'agentCode', width: '100px' },
    { title: '客户名称', dataIndex: 'agentName', width: '200px' },
    // { title: '客户类型', dataIndex: 'agentType', width: '100px', render: (text, reoled, index) => '经销商' },
    { title: '品牌公司', dataIndex: 'brandName', width: '200px' },
    { title: '联系人姓名', dataIndex: 'contact', width: '100px' },
    { title: '业务员姓名', dataIndex: 'businessPersonName', width: '100px' },
    { title: '省', dataIndex: 'provinceName', width: '100px' },
    { title: '市', dataIndex: 'cityName', width: '100px' },
    { title: '区', dataIndex: 'districtName', width: '100px' },
    { title: '联系人电话', dataIndex: 'phone', width: '100px' },
    { title: '经营税号', dataIndex: 'socialCode', width: '100px' },
    { title: '联系地址', dataIndex: 'address', width: '200px' },
    {
      title: '操作',
      dataIndex: 'operate',
      width: '250px',
      fixed: 'right',
      render: columnRenders.operate(
        [
          { title: '查看下级客户', action: (text, record) => this.handSelectLowerLevelData(record) },
          // {
          //   title: '编辑',
          //   auth: EditBtnAuth,
          //   action: (text, row) => this.edit(row),
          // },
          // {
          //   title: '维护品牌信息',
          //   auth: BrandBtnAuth,
          //   action: (text, row) => {
          //     this.props.history.push(`/customer/list/edit/${row?.agentName}/${row?.agentCode}`)
          //   },
          // },
          {
            title: '查看详情',
            auth: DetailBtnAuth,
            action: (text, row) => this.toDetail(row),
          },{
            title: '客户明细',
            action: (text, record) => this.handGetCustomerDetailsData(record),
          },
        ],
      ),
    },
  ]
  state = {
    loading: false,
    uploading: false,
    downloading: false,
    title: '客户管理',
    page: 1,
    size: 10,
    total: 0,
    searchValues: {
      brandCode: this.brandList[0].value,
      agentType: 0,
    },
    dataSource: [],
    conditions: [
      {
        label: '品牌公司',
        id: 'brandCode',
        initialValue: this.brandList[0].value,
        render: (
          <UdSelect
            showSearch
            allowClear={true}
            options={this.brandList}
            onChange={value => {
              this.changeBrandCode(value)
            }}
          />
        ),
      },
      {
        label: '所属组织',
        id: 'belongAreaCode',
        render: () => (
          <TreeSelect showSearch treeNodeFilterProp="title">
            {this.mapTree(this.state.treeDataList)}
          </TreeSelect>
        ),
      },
      { id: 'agentCode', label: '客户编码' },
      { id: 'agentName', label: '客户名称' },
      { id: 'businessPersonName', label: '业务员姓名' },
      {
        id: 'isValid',
        label: '状态',
        render: (
          <Select>
            <Option value={1}>启用</Option>
            <Option value={0}>禁用</Option>
          </Select>
        ),
      },
      {
        id: 'openCheckStock',
        label: '盘点权限',
        render: (
          <Select>
            <Option value="Y">启用</Option>
            <Option value="N">禁用</Option>
          </Select>
        ),
      },
      {
        id: 'openQuota',
        label: '配额申请权限',
        render: (
          <Select>
            <Option value="Y">启用</Option>
            <Option value="N">禁用</Option>
          </Select>
        ),
      },
      {
        id: 'allowEditStock',
        label: '期初库存、期间开单数编辑权限',
        labelCol: { span: 9 },
        wrapperCol: { span: 15 },
        render: (
          <Select>
            <Option value="Y">启用</Option>
            <Option value="N">禁用</Option>
          </Select>
        ),
      },
    ],
    brandCompanies: [],
    treeDataList: [],
  }

  private mapTree = (data: any[]) => {
    return data.map(item => {
      return (
        <TreeNode value={item.code} title={item.name} key={item.code}>
          {this.mapTree(item?.children || [])}
        </TreeNode>
      )
    })
  }
  private changeBrandCode = (value: any) => {
    this.filterForm.setFieldsValue({ prodBarcode: undefined, belongAreaCode: undefined }, () => {
      this.setState({ treeDataList: [] }, () => {
        Promise.allSettled([this.getAreaList(value)]).then((res: any) => {
          this.setState({
            treeDataList: res[0]?.value || [],
          })
        })
      })
    })
  }
  private handGetCustomerDetailsData = (record: Record<string, any>): void => {
    UdDrawer.open({
      title: '客户明细',
      cancelText: null,
      width: '80%',
      content: <CustomerDetailsTable record={record}/>,
    })
  }
  private getAreaList = (value: any) => {
    if (Object.is(value, undefined)) return []
    return http
      .get(apis.getTreeByUser, {
        params: { organizationCode: value },
      })
      .then(res => {
        let data = res?.data?.children || []
        return data
      })
  }

  private handSelectLowerLevelData = (record): void => {
    UdDrawer.open({
      title: '下级客户信息',
      cancelText: null,
      width: '80%',
      content: (
        <SelectLowerTable
          brandList={this.brandList}
          brandCode={record.brandCode}
          acctName={record.agentName}
          acctCode={record.agentCode}
        />
      ),
    })
  }

  public componentDidMount() {
    this.getRecordTableData()
  }
  render() {
    let { loading, uploading, downloading, conditions, dataSource, page, size, total } = this.state
    return (
      <Spin spinning={uploading || downloading} tip={uploading ? '上传中，请稍后...' : '请求中，请稍后...'}>
        <UdFilter
          getForm={form => {
            this.filterForm = form
          }}
          items={conditions}
          onSearch={values => {
            this.handleSearch(values)
          }}
          loading={loading}
          resetAfter={this.resetFilterHandle}
        />
        <UdToolbar
          other={
            <Button.Group>
              {/* {uaaApp.canUse(AddBtnAuth) && (
                <Button
                  type="primary"
                  style={{ marginRight: 10 }}
                  onClick={() => {
                    this.props.history.push('/customer/list/add')
                  }}
                >
                  新增
                </Button>
              )} */}
              {uaaApp.canUse(exportCustomersTable) && (
                <Button
                  type="primary"
                  style={{ marginRight: 10 }}
                  onClick={() => {
                    this.exportCustomersTable()
                  }}
                >
                  导出
                </Button>
              )}
            </Button.Group>
          }
        ></UdToolbar>
        <UdTable
          rowKey="id"
          loading={loading}
          columns={this.columns}
          dataSource={dataSource}
          onChange={this.handleChangePage}
          scroll={{ x: true }}
          pagination={{
            current: page,
            pageSize: size,
            total: total,
            showSizeChanger: true,
            pageSizeOptions: ['10', '20', '30', '40'],
            showTotal: (total, range) => `共${total}项，当前${range[0]}-${range[1]}项`,
          }}
        ></UdTable>
      </Spin>
    )
  }

  private handleChangePage = pagination => {
    const { current: page, pageSize: size } = pagination
    this.setState({ page, size }, () => {
      this.getRecordTableData()
    })
  }

  private handleSearch = (values: object) => {
    this.setState({ searchValues: { ...values, agentType: 0 }, dataSource: [], page: 1, total: 0 }, () => {
      this.getRecordTableData()
    })
  }

  private resetFilterHandle = (form: WrappedFormUtils) => {
    this.setState(
      { searchValues: { ...form.getFieldsValue(), agentType: 0 }, dataSource: [], page: 1, total: 0 },
      () => {
        this.getRecordTableData()
      }
    )
  }

  private getRecordTableData = async () => {
    this.setState({ loading: true })
    let { page, size, searchValues } = this.state
    http
      .post(customerApis.CustomerList, {
        page,
        size,
        ...searchValues,
      })
      .then(res => {
        const dataSource = res.data?.content
        this.setState({
          dataSource,
          total: res.data.totalElements,
        })
      })
      .finally(() => {
        this.setState({
          loading: false,
        })
      })
  }

  //导出
  private exportCustomersTable = () => {
    let { searchValues } = this.state
    const params = {...searchValues}
    this.setState({ downloading: true })
    http
      .post(customerApis.exportCustomersTable, params, { responseType: 'arraybuffer' })
      .then(res => {
        if (!res.data.code) {
          downBlobFile(res.data, '经销商客户数据表')
        }
      })
      .finally(() => {
        this.setState({ downloading: false })
      })
  }

  private toDetail = row => {
    const { id, agentType = '0', agentCode, belongAreaCode, brandCode, agentName } = row
    this.props.history.push(
      '/customer/detail/' +
        id +
        '/' +
        agentType +
        '?agentCode=' +
        agentCode +
        '&belongAreaCode=' +
        belongAreaCode +
        '&brandCode=' +
        brandCode +
        '&agentName=' +
        agentName
    )
  }

  //编辑
  private edit = row => {
    row.agentType = +row.agentType
    UdModal.open({
      title: '编辑客户基本信息',
      content: (
        <UdModalForm
          items={[
            {
              id: 'agentName',
              label: '客户名称',
              render: <Input disabled />,
            },
            {
              id: 'agentCode',
              label: '客户编码',
              render: <Input disabled />,
            },
            {
              id: 'agentType',
              label: '客户类型',
              render: (
                <Select disabled>
                  <Select.Option value={0}>经销商</Select.Option>
                </Select>
              ),
            },
            {
              id: 'address',
              label: '联系地址',
              rules: [validators.required, validators.max(100)],
            },
            {
              id: 'contact',
              label: '联系人',
              rules: [validators.required, validators.userName, validators.max(10)],
            },
            {
              id: 'phone',
              label: '联系电话',
              rules: [validators.required, validators.phoneCommonly],
            },
            { id: 'socialCode', label: '税号', rules: [validators.required, validators.max(20)] },
          ]}
          values={row}
        />
      ),
      onOk: value => {
        return http.put(anounApis.SendToListOfCustomer, { ...value }).then(() => {
          message.success('操作成功')
          let ZdParams = {
            brandCode: row.brandCode,
            dealerCode: row.agentCode,
          }
          this.getRecordTableData()
          http.post(anounApis.pushUpdateDealerZd, { ...ZdParams }).then(res => {
            message.success('同步成功')
          })
        })
      },
    })
  }
}
export default withRouter(DealerDataTable);